/**
 * 
 */
package com.pxingg.voice;

import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.pxingg.exception.XException;

/**
 * @author pxingg
 * 
 */
public class WavPlayer
{
    /**
     * The log of this class
     */
    static Log log = LogFactory.getLog(WavPlayer.class);

    /**
     * Play specify wav data
     * 
     * @param wav
     *            the wav data to play
     * @throws XException
     */
    public void play(final WavData wav) throws XException
    {
        SourceDataLine line = null;
        try
        {
            final DataLine.Info info = new DataLine.Info(SourceDataLine.class, wav.getFormat());
            line = (SourceDataLine) AudioSystem.getLine(info);

            final byte[] data = wav.getData();
            line.open(wav.getFormat(), data.length);
            // start the line
            line.start();
            line.write(data, 0, data.length);

            // wait until all data is played, then close the line
            line.drain();
            line.close();
        }
        catch (final LineUnavailableException e)
        {
            WavPlayer.log.error(e);
            throw new XException(e);
        }
        finally
        {
            if (line != null)
            {
                line.close();
            }
        }

    }
}
